import { memo } from 'react'
import styles from './index.module.less'
import cm from 'classnames'
import Null from '../null-data'
import Loading from '../fetch-loading'

// 用来给列确定宽度用的
const itemStyle = (item) => {
  const styles = {
    paddingLeft: item.left || 0,
    paddingRight: item.right || 0,
  }
  if (item.noEllipsis) {
    styles.width = item.width
  } else {
    styles.flex = item.width
  }
  return styles
}

const renderRow = (column, data) => {
  if (column.render) {
    return column.render(data, data[column.dataIndex])
  } else {
    return data[column.dataIndex]
  }
}

const Index = (props) => {
  const { columns, rowStyle = {}, dataSource, rowKeyName = 'id', className, nullText = '暂无数据' } = props

  return (
    <div className={cm(styles.table, className)}>
      {!dataSource ? (
        <Loading className="flex justify-center my-20" />
      ) : !dataSource.length ? (
        <Null content={nullText} />
      ) : (
        <>
          <div className={styles.tableHeader}>
            {columns.map((item, index) => {
              return (
                <div
                  key={index}
                  style={itemStyle(item)}
                  className={cm(
                    styles.headerItem,
                    !item.noEllipsis ? 'textEllipsis' : '',
                    item.headerAlign || 'text-center'
                  )}
                >
                  {item.title}
                </div>
              )
            })}
          </div>
          <div className={styles.tableBody}>
            {dataSource.map((data, index) => {
              return (
                <div key={data[rowKeyName] || index} className={styles.tableRowBox}>
                  <div className={styles.tableRow} style={rowStyle}>
                    {columns.map((item, index) => {
                      return (
                        <div
                          title={item.needHover ? data[item.dataIndex] : ''}
                          key={index}
                          style={itemStyle(item)}
                          className={cm(
                            {
                              'overflow-hidden': !item.show,
                              textEllipsis: !item.noEllipsis && !item.show,
                            },
                            item.bodyAlign || 'text-center'
                          )}
                        >
                          {renderRow(item, data)}
                        </div>
                      )
                    })}
                  </div>
                </div>
              )
            })}
          </div>
        </>
      )}
    </div>
  )
}

const Table = memo(Index)
export default Table
